import _ from 'lodash'
import { points } from '@/utils/config'
import { TColor } from './types'

export const getGameColor = (): TColor => {
  const colors = ['red', 'green', 'yellow']
  const weights = [47.5, 47.5, 5]
  const cumulativeWeights = weights.reduce((acc: Array<number>, weight: number, index: number) => {
    acc.push((acc[index - 1] || 0) + weight)
    return acc
  }, [])
  const totalWeight = cumulativeWeights[cumulativeWeights.length - 1]
  const randomNum = Math.random() * totalWeight
  const selectedIndex = _.findIndex(cumulativeWeights, weight => randomNum < weight)
  return colors[selectedIndex] as TColor
}

export const getGamePoint = (): number => {
  const weights = {
    apple: 5,
    small: 3, 
    large: 1, 
    large2: 2
  }
  const selected = points.filter(point => point.isFruit)
  const weightedPoints = selected.map((point) => {
    let weight = 0
    if (point.alias === 'apple') {
      weight = weights.apple
    } else if (point.type === 'small') {
      weight = weights.small
    } else if (point.type === 'large') {
      if (['star', 'seven', 'watermelon'].includes(point.alias || '')) {
        weight = weights.large2
      } else {
        weight = weights.large
      }
    }
    return { ...point, weight }
  })
  const totalWeight = weightedPoints.reduce((acc, point) => acc + point.weight, 0)
  const randomValue = Math.random() * totalWeight
  let cumulativeWeight = 0
  for (let i = 0; i < weightedPoints.length; i++) {
    cumulativeWeight += weightedPoints[i].weight
    if (randomValue <= cumulativeWeight) {
      return i
    }
  }
  return 0
}